package com.haltakov.letterjumble.game.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class LanguageInfo {
	String name;
	Locale locale;

	int letterCount;
	Map<Character, Letter> letters; 

	public LanguageInfo(String languageFile) throws LanguageFileException {
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			Document doc = factory.newDocumentBuilder().parse(languageFile);

			locale = new Locale(doc.getElementsByTagName("locale").item(0).getTextContent());   
			name = doc.getElementsByTagName("name").item(0).getTextContent();
			letterCount = Integer.parseInt(doc.getElementsByTagName("lettercount").item(0).getTextContent());

			letters = new HashMap<Character, Letter>(letterCount*2);

			XMLHelpers.removeWhitespaceNodes(doc.getDocumentElement());

			NodeList lettersList = doc.getElementsByTagName("letter");
			for (int i=0; i<lettersList.getLength(); ++i) {
				String lt = lettersList.item(i).getChildNodes().item(0).getTextContent();
				char l;
				if (lt.isEmpty())
					l = ' ';
				else
					l = lt.charAt(0);
				letters.put(l, new Letter(l, Integer.valueOf(lettersList.item(i).getChildNodes().item(1).getTextContent()), Integer.valueOf(lettersList.item(i).getChildNodes().item(2).getTextContent())));
			}

		} catch (SAXException e) {
			throw new LanguageFileException("Error parsing language file!");
		} catch (IOException e) {
			throw new LanguageFileException("Error loading language file!");
		} catch (ParserConfigurationException e) {
			throw new LanguageFileException("Error parsing language file!");
		}
	}

	public Letter getLetter(char c) {
		return letters.get(c);
	}

	public int getLetterCount() {
		return letterCount;
	}

	public String getName() {
		return name;
	}

	public Locale getLocale() {
		return locale;
	}

	public Iterator<Letter> letterIterator() {
		return letters.values().iterator();
	}
}